package com.wisdytech.common.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.util.AttributeKey;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private static final Logger log = LoggerFactory.getLogger(HttpRequestHandler.class);

    private final String webSocketUri;

    public static final AttributeKey<String> ZUTAIID = AttributeKey.valueOf("zutaiId");
    public static final AttributeKey<String> TIME = AttributeKey.valueOf("time");

    public HttpRequestHandler(String webSocketUri) {
        this.webSocketUri = webSocketUri;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        log.info("===========> {}, {}", webSocketUri, request.uri());
        String uri = StringUtils.substringBefore(request.uri(), "?");
        if(webSocketUri.equalsIgnoreCase(uri)) {//获取webSocket参数
            QueryStringDecoder query = new QueryStringDecoder(request.uri());
            Map<String, List<String>> map = query.parameters();
            //组态Id
            String zutaiId = map.get("id").get(0);
            //时间戳，确保唯一
            String time = map.get("time").get(0);
            log.info("connect with zutaiId[{}],time[{}]",zutaiId,time);
            ctx.channel().attr(ZUTAIID).getAndSet(zutaiId);
            ctx.channel().attr(TIME).getAndSet(time);
            request.setUri(uri);
            //将处理后的结果发送至下一个handler
            ctx.fireChannelRead(request.retain());
        }
    }
}
